module Payers
  class AcademicPartitionsController < ControllerBase
    def index
      # cached "academic_partitions:index:#{params[:parent_id]}" do
      return head :not_found unless params[:plan_id]
      plan = Plan.find_by(id: params[:plan_id])
      return head :not_found unless plan

      if params[:parent_id]
        exists = AcademicPartitionHierarchy.where(descendant_id: params[:parent_id])
                     .where(ancestor_id: plan.targets.pluck(:academic_partition_id))
                     .exists?
        return head :not_found unless exists
        @academic_partitions = AcademicPartition.where(parent_id: params[:parent_id])
        render json: @academic_partitions, each_serializer: AcademicPartitionSerializer
      else
        render json: plan.academic_partitions, each_serializer: AcademicPartitionSerializer
      end
      # end
    end
  end
end
